using AuthService.Domain.Common;
using AuthService.Domain.Enums;
using System.ComponentModel.DataAnnotations;
using System.Text.Json;
using HttpMethod = AuthService.Domain.Enums.HttpMethod;

namespace AuthService.Domain.Entities;

/// <summary>
/// 动态API端点实体类
/// 支持运行时配置和管理API端点
/// </summary>
public class DynamicApiEndpoint : BaseEntity
{
    /// <summary>
    /// API端点名称
    /// </summary>
    [Required]
    [StringLength(100)]
    public string Name { get; set; } = string.Empty;

    /// <summary>
    /// API端点描述
    /// </summary>
    [StringLength(500)]
    public string? Description { get; set; }

    /// <summary>
    /// HTTP方法（GET, POST, PUT, DELETE等）
    /// </summary>
    [Required]
    public HttpMethod Method { get; set; } = HttpMethod.Get;

    /// <summary>
    /// API路径模板（如：/api/users/{id}）
    /// </summary>
    [Required]
    [StringLength(500)]
    public string PathTemplate { get; set; } = string.Empty;

    /// <summary>
    /// 目标服务名称（用于服务发现）
    /// </summary>
    [StringLength(100)]
    public string? TargetService { get; set; }

    /// <summary>
    /// 目标URL（完整的后端服务URL）
    /// </summary>
    [StringLength(1000)]
    public string? TargetUrl { get; set; }

    /// <summary>
    /// 是否启用此端点
    /// </summary>
    public bool IsEnabled { get; set; } = true;

    /// <summary>
    /// 是否需要认证
    /// </summary>
    public bool RequireAuthentication { get; set; } = true;

    /// <summary>
    /// 所需的角色列表（JSON数组格式）
    /// </summary>
    public List<string> RequiredRoles { get; set; } = new();

    /// <summary>
    /// 所需的权限列表（JSON数组格式）
    /// </summary>
    public List<string> RequiredPermissions { get; set; } = new();

    /// <summary>
    /// 限流配置（每分钟请求数）
    /// </summary>
    public int? RateLimitPerMinute { get; set; }

    /// <summary>
    /// 超时时间（秒）
    /// </summary>
    public int TimeoutSeconds { get; set; } = 30;

    /// <summary>
    /// 重试次数
    /// </summary>
    public int RetryCount { get; set; } = 0;

    /// <summary>
    /// 缓存时间（秒，0表示不缓存）
    /// </summary>
    public int CacheSeconds { get; set; } = 0;

    /// <summary>
    /// 请求头配置（JSON格式）
    /// </summary>
    public Dictionary<string, string> Headers { get; set; } = new();

    /// <summary>
    /// 查询参数配置（JSON格式）
    /// </summary>
    public Dictionary<string, string> QueryParameters { get; set; } = new();

    /// <summary>
    /// 请求体转换规则（JSON格式）
    /// </summary>
    public string? RequestTransformation { get; set; }

    /// <summary>
    /// 响应体转换规则（JSON格式）
    /// </summary>
    public string? ResponseTransformation { get; set; }

    /// <summary>
    /// API版本
    /// </summary>
    [StringLength(20)]
    public string Version { get; set; } = "1.0";

    /// <summary>
    /// 标签列表（用于分类和搜索）
    /// </summary>
    public List<string> Tags { get; set; } = new();

    /// <summary>
    /// 租户ID（多租户支持）
    /// </summary>
    [StringLength(50)]
    public string? TenantId { get; set; }

    /// <summary>
    /// 优先级（数字越大优先级越高）
    /// </summary>
    public int Priority { get; set; } = 0;

    /// <summary>
    /// 扩展元数据（JSON格式）
    /// </summary>
    public string? Metadata { get; set; }

    /// <summary>
    /// 最后访问时间
    /// </summary>
    public DateTime? LastAccessedAt { get; set; }

    /// <summary>
    /// 访问次数统计
    /// </summary>
    public long AccessCount { get; set; } = 0;

    /// <summary>
    /// 验证端点配置是否有效
    /// </summary>
    /// <returns>验证结果</returns>
    public ValidationResult ValidateConfiguration()
    {
        var errors = new List<string>();

        // 验证路径模板
        if (string.IsNullOrWhiteSpace(PathTemplate))
        {
            errors.Add("路径模板不能为空");
        }
        else if (!PathTemplate.StartsWith('/'))
        {
            errors.Add("路径模板必须以'/'开头");
        }

        // 验证目标配置
        if (string.IsNullOrWhiteSpace(TargetService) && string.IsNullOrWhiteSpace(TargetUrl))
        {
            errors.Add("必须指定目标服务名称或目标URL");
        }

        // 验证URL格式
        if (!string.IsNullOrWhiteSpace(TargetUrl) && !Uri.TryCreate(TargetUrl, UriKind.Absolute, out _))
        {
            errors.Add("目标URL格式无效");
        }

        // 验证超时时间
        if (TimeoutSeconds <= 0)
        {
            errors.Add("超时时间必须大于0");
        }

        // 验证重试次数
        if (RetryCount < 0)
        {
            errors.Add("重试次数不能为负数");
        }

        // 验证缓存时间
        if (CacheSeconds < 0)
        {
            errors.Add("缓存时间不能为负数");
        }

        return new ValidationResult
        {
            IsValid = errors.Count == 0,
            Errors = errors
        };
    }

    /// <summary>
    /// 检查用户是否有权限访问此端点
    /// </summary>
    /// <param name="userRoles">用户角色列表</param>
    /// <param name="userPermissions">用户权限列表</param>
    /// <returns>是否有权限</returns>
    public bool CheckAccess(IEnumerable<string> userRoles, IEnumerable<string> userPermissions)
    {
        // 如果不需要认证，直接允许访问
        if (!RequireAuthentication)
            return true;

        var roles = userRoles?.ToList() ?? new List<string>();
        var permissions = userPermissions?.ToList() ?? new List<string>();

        // 检查角色权限
        if (RequiredRoles.Any())
        {
            var hasRequiredRole = RequiredRoles.Any(requiredRole =>
                roles.Contains(requiredRole, StringComparer.OrdinalIgnoreCase));

            if (!hasRequiredRole)
                return false;
        }

        // 检查具体权限
        if (RequiredPermissions.Any())
        {
            var hasRequiredPermission = RequiredPermissions.Any(requiredPermission =>
                permissions.Contains(requiredPermission, StringComparer.OrdinalIgnoreCase));

            if (!hasRequiredPermission)
                return false;
        }

        return true;
    }

    /// <summary>
    /// 记录访问
    /// </summary>
    public void RecordAccess()
    {
        LastAccessedAt = DateTime.UtcNow;
        AccessCount++;
        MarkAsUpdated();
    }

    /// <summary>
    /// 添加必需角色
    /// </summary>
    /// <param name="role">角色名称</param>
    /// <param name="updatedBy">更新者</param>
    public void AddRequiredRole(string role, string? updatedBy = null)
    {
        if (string.IsNullOrWhiteSpace(role))
            throw new ArgumentException("角色名称不能为空", nameof(role));

        if (!RequiredRoles.Contains(role, StringComparer.OrdinalIgnoreCase))
        {
            RequiredRoles.Add(role);
            MarkAsUpdated(updatedBy);
        }
    }

    /// <summary>
    /// 移除必需角色
    /// </summary>
    /// <param name="role">角色名称</param>
    /// <param name="updatedBy">更新者</param>
    public void RemoveRequiredRole(string role, string? updatedBy = null)
    {
        if (RequiredRoles.RemoveAll(r => string.Equals(r, role, StringComparison.OrdinalIgnoreCase)) > 0)
        {
            MarkAsUpdated(updatedBy);
        }
    }

    /// <summary>
    /// 添加必需权限
    /// </summary>
    /// <param name="permission">权限名称</param>
    /// <param name="updatedBy">更新者</param>
    public void AddRequiredPermission(string permission, string? updatedBy = null)
    {
        if (string.IsNullOrWhiteSpace(permission))
            throw new ArgumentException("权限名称不能为空", nameof(permission));

        if (!RequiredPermissions.Contains(permission, StringComparer.OrdinalIgnoreCase))
        {
            RequiredPermissions.Add(permission);
            MarkAsUpdated(updatedBy);
        }
    }

    /// <summary>
    /// 移除必需权限
    /// </summary>
    /// <param name="permission">权限名称</param>
    /// <param name="updatedBy">更新者</param>
    public void RemoveRequiredPermission(string permission, string? updatedBy = null)
    {
        if (RequiredPermissions.RemoveAll(p => string.Equals(p, permission, StringComparison.OrdinalIgnoreCase)) > 0)
        {
            MarkAsUpdated(updatedBy);
        }
    }

    /// <summary>
    /// 添加标签
    /// </summary>
    /// <param name="tag">标签名称</param>
    /// <param name="updatedBy">更新者</param>
    public void AddTag(string tag, string? updatedBy = null)
    {
        if (string.IsNullOrWhiteSpace(tag))
            throw new ArgumentException("标签名称不能为空", nameof(tag));

        if (!Tags.Contains(tag, StringComparer.OrdinalIgnoreCase))
        {
            Tags.Add(tag);
            MarkAsUpdated(updatedBy);
        }
    }

    /// <summary>
    /// 移除标签
    /// </summary>
    /// <param name="tag">标签名称</param>
    /// <param name="updatedBy">更新者</param>
    public void RemoveTag(string tag, string? updatedBy = null)
    {
        if (Tags.RemoveAll(t => string.Equals(t, tag, StringComparison.OrdinalIgnoreCase)) > 0)
        {
            MarkAsUpdated(updatedBy);
        }
    }

    /// <summary>
    /// 启用端点
    /// </summary>
    /// <param name="updatedBy">更新者</param>
    public void Enable(string? updatedBy = null)
    {
        IsEnabled = true;
        MarkAsUpdated(updatedBy);
    }

    /// <summary>
    /// 禁用端点
    /// </summary>
    /// <param name="updatedBy">更新者</param>
    public void Disable(string? updatedBy = null)
    {
        IsEnabled = false;
        MarkAsUpdated(updatedBy);
    }
}

/// <summary>
/// 验证结果类
/// </summary>
public class ValidationResult
{
    /// <summary>
    /// 是否验证通过
    /// </summary>
    public bool IsValid { get; set; }

    /// <summary>
    /// 错误信息列表
    /// </summary>
    public List<string> Errors { get; set; } = new();
}
